package com.tanhua.manage.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.manage.domain.Admin;
import com.tanhua.manage.exception.BusinessException;
import com.tanhua.manage.mapper.AdminMapper;
import com.tanhua.manage.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AdminService extends ServiceImpl<AdminMapper, Admin> {

    private static final String CACHE_KEY_CAP_PREFIX = "MANAGE_CAP_";
    public static final String CACHE_KEY_TOKEN_PREFIX = "MANAGE_TOKEN_";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private JwtUtils jwtUtils;

    public Map<String, String> login(Map<String, String> paremMap) {
        String uuid = paremMap.get("uuid");
        String key = CACHE_KEY_CAP_PREFIX + uuid;
        String redisVerificationCode = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(redisVerificationCode)) {
            throw new BusinessException("请重新获取验证码");
        }
        if (!StringUtils.equals(paremMap.get("verificationCode"), redisVerificationCode)) {
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(key);
        Admin loginUser = query().eq("username", paremMap.get("username")).one();
        String password = paremMap.get("password");
        password = SecureUtil.md5(password);
      if (null==loginUser || !StringUtils.equals(password,loginUser.getPassword())){
          throw new BusinessException("用户名或验证码错误");
      }
        String token = jwtUtils.createJWT(loginUser.getUsername(), loginUser.getId());
        String tokenKey = CACHE_KEY_TOKEN_PREFIX + token;
        String loginUserTojson = JSON.toJSONString(loginUser);
        redisTemplate.opsForValue().set(tokenKey,loginUserTojson,30,TimeUnit.MINUTES);
        Map<String,String> tokenMap=new HashedMap();
        tokenMap.put("token",token);
        return tokenMap;
    }

    /**
     * 保存生成的验证码
     *
     * @param uuid
     * @param code
     */
    public void saveCode(String uuid, String code) {
        String key = CACHE_KEY_CAP_PREFIX + uuid;
        // 缓存验证码，10分钟后失效
        redisTemplate.opsForValue().set(key, code, Duration.ofMinutes(10));
    }

    /**
     * 获取登陆用户信息
     *
     * @return
     */
    public Admin getByToken(String authorization) {
        String token = authorization.replaceFirst("Bearer ", "");
        String tokenKey = CACHE_KEY_TOKEN_PREFIX + token;
        String adminString = (String) redisTemplate.opsForValue().get(tokenKey);
        Admin admin = null;
        if (StringUtils.isNotEmpty(adminString)) {
            admin = JSON.parseObject(adminString, Admin.class);
            // 延长有效期 30分钟
            redisTemplate.expire(tokenKey, 30, TimeUnit.MINUTES);
        }
        return admin;
    }

    public void logout(String token) {
        String realToken = token.replace("Bearer", "");
        String key= CACHE_KEY_TOKEN_PREFIX + realToken;
        redisTemplate.delete(key);
    }
}
